package cn.fotoit.product.system.service;
import cn.fotoit.product.system.entity.Role;
import cn.fotoit.product.system.repository.RoleRepository;
import cn.fotoit.product.util.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;


@Service
@CacheConfig(cacheNames = "queue_management_roleService")
@Transactional(readOnly = true)
public class RoleService {
    @Autowired
    private RoleRepository roleRepository;

    @CacheEvict(allEntries = true,cacheNames = {"queue_management_permissionService","queue_management_roleRelPermissionService","queue_management_roleService","queue_management_userService"})
    @Transactional
    public void add(Role role) {
        roleRepository.save(role);
    }

    @CacheEvict(allEntries = true,cacheNames = {"queue_management_permissionService","queue_management_roleRelPermissionService","queue_management_roleService","queue_management_userService"})
    @Transactional
    public void deleteById(Integer id) {
        roleRepository.deleteById(id);
    }

    @CacheEvict(allEntries = true,cacheNames = {"queue_management_permissionService","queue_management_roleRelPermissionService","queue_management_roleService","queue_management_userService"})
    @Transactional
    public void updateNotNull(Role role) {
        Optional<Role> byId = roleRepository.findById(role.getId());
        if (byId.isPresent()) {
            Role obj = byId.get();
            BeanUtil.copyPropertiesIgnoreNull(role, obj);
            roleRepository.save(obj);
        }
    }

    @Cacheable(key = "'findAll'+#page+'size'+#size")
    public Page<Role> findAll(Integer page, Integer size) {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page - 1, size, sort);
        return roleRepository.findAll(pageable);
    }

    @Cacheable(key = "'findById'+#id")
    public Role findById(Integer id) {
        Optional<Role> byId = roleRepository.findById(id);
        if (byId.isPresent()) {
            return byId.get();
        }
        return null;
    }

}